package com.example.child_protection.util;

import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.reflect.ConstructorUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

public class InstantiateUtils {public static <R> R instantiate(Class<R> clazz ) {
    Validate.notNull( clazz, "Class is null", new Object[0] );

    Constructor<R> constructor = null;
    try {
        constructor = ConstructorUtils.getAccessibleConstructor( clazz, new Class[0] );
    } catch ( Exception e ) {
        throw new RuntimeException(
                "no default (no-argument) constructor for class: " + clazz.getName() + " (class must be instantiated by Interceptor)",
                e );
    }

    int modifier = clazz.getModifiers();
    if ( ( Modifier.isAbstract( modifier ) ) || ( Modifier.isInterface( modifier ) ) ) {
        throw new RuntimeException( "Cannot instantiate abstract class or interface: " + clazz.getName() );
    }

    if ( null == constructor ) {
        throw new RuntimeException( "No default constructor for result: " + clazz.getName() );
    }
    try {
        return ( R ) constructor.newInstance( ( Object[] ) null );
    } catch ( Exception e ) {
    }
    throw new RuntimeException( "Could not instantiate result: " + clazz.getName() );
}

}
